﻿using System.Collections.Generic;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;

namespace RockBus.ServiceModel
{
    public class MessageConverter<TMessageContract>
        where TMessageContract : class
    {
        private static readonly Dictionary<string, TypedMessageConverter> _converterDictionary = new Dictionary<string, TypedMessageConverter>();

        private static Dictionary<string, TypedMessageConverter> ConverterDictionary
        {
            get { return _converterDictionary; }
        }

        public static Message ConvertMessageContractToUntypedMessage(TMessageContract messageContract, string action)
        {
            AssertMessageConverter(action);
            return MessageConverter<TMessageContract>.ConverterDictionary[action].ToMessage(messageContract);
        }

        public static Message ConvertMessageContractToUntypedMessage(TMessageContract messageContract, string action, MessageVersion version)
        {
            AssertMessageConverter(action);
            return MessageConverter<TMessageContract>.ConverterDictionary[action].ToMessage(messageContract, version);
        }

        public static TMessageContract ConvertUntypedMessageToMessageContract(Message message)
        {
            return ConvertUntypedMessageToMessageContract(message, "*");
        }

        public static TMessageContract ConvertUntypedMessageToMessageContract(Message message, string action)
        {
            AssertMessageConverter(action);
            return (TMessageContract)MessageConverter<TMessageContract>.ConverterDictionary[action].FromMessage(message);
        }

        private static object _lockObject = new object();

        private static void AssertMessageConverter(string action)
        {
            if (!MessageConverter<TMessageContract>.ConverterDictionary.ContainsKey(action))
            {
                lock (_lockObject)
                {
                    if (!MessageConverter<TMessageContract>.ConverterDictionary.ContainsKey(action))
                    {
                        TypedMessageConverter tmc = TypedMessageConverter.Create(typeof(TMessageContract), action);
                        MessageConverter<TMessageContract>.ConverterDictionary.Add(action, tmc);
                    }
                }
            }
        }
    }
}